package app.beit.finportal.controller.backdoor;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import app.beit.finportal.bean.MenuBean;
import app.beit.finportal.config.MasterConfig;
import app.beit.finportal.config.MenuConfig;
import app.beit.finportal.controller.BaseController;
import app.beit.finportal.service.MenuService;
import app.beit.finportal.utils.constr.SessionConstr;

@Controller
@RequestMapping("/backend/menu")
public class BackdoorMenuController extends BaseController{

	@Autowired
	private MenuService menuService;
	
	@RequestMapping
	public String init(final HttpServletRequest request){
		try {
			super.startProcess(request);
			request.setAttribute(SessionConstr.ACTIVE_PAGE, "menus");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "backend.menu";
	}
	
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/reset", method=RequestMethod.POST)
	public String reset(final HttpServletRequest request){
		try {
			final List<MenuBean> menuBeans = MenuConfig.getInstance().getListMenu();
		    final Enumeration requestParameters = request.getParameterNames();

		    Map<String, String> maps = new HashMap<String, String>();
		    while (requestParameters.hasMoreElements()) {
		        final String element = (String) requestParameters.nextElement();
		        final String value = request.getParameter(element);
		        maps.put(element, value);
		    }
		    
		    for(MenuBean b : menuBeans){
		    	final String id = b.getId().toString();
		    	final String value = maps.get(id);
			    if(value != null && value.length() > 0){
		        	b.setIsActive('Y');
			    }else{
		        	b.setIsActive('N');
			    }
		    }
		    boolean complete = this.menuService.updateListMenu(menuBeans);
		    if(complete){
		    	MenuConfig.getInstance().setNewInstance();
		    	MasterConfig.getInstance().setDeployBean(null);
		    	super.startProcess(request);
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute(SessionConstr.ACTIVE_PAGE, "menus");
		return "redirect:";
	}
	
}
